package bdqn.servlet;

import bdqn.pojo.Person;
import bdqn.service.PersonService;
import bdqn.service.impl.PersonServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "PersonServlet")
public class PersonServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();
        String opr = request.getParameter("opr");
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

        PersonService personService = (PersonService)context.getBean("PersonService");
        if(opr==null){
            List<Person> list = personService.getLsitInfo();
            session.setAttribute("list",list);
            response.sendRedirect("index.jsp");
        }else if("add".equals(opr)){
            response.sendRedirect("add.jsp");
        }



    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

        PersonService personService = (PersonService)context.getBean("PersonService");
        String opr = request.getParameter("opr");
        if("add".equals(opr)){
            String name =request.getParameter("name");
            String gender =request.getParameter("gender");
            String age =request.getParameter("age");
            String rank =request.getParameter("rank");
            String department =request.getParameter("department");

            Person ps = new Person();
            ps.setRank(rank);
            ps.setGender(gender);
            ps.setAge(Integer.parseInt(age));
            ps.setDepartment(department);
            ps.setName(name);
            int count = personService.add(ps);
            if (count == 1) {
                out.print("<script>alert('添加成功');location.href='PersonServlet';</script>");
            } else {
                out.print("<script>alert('失败');history.back();</script>");
            }


        }

    }
}
